<?php
/**
 * 文件上传
 * ============================================================================
 * 网站地址: http://www.pcfcms.com
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 小潘 <1131680521@qq.com>
 * Date: 2019-12-21
 */
namespace app\home\controller\user;
use think\facade\Request;
use think\facade\Db;
use think\facade\Session;
use think\facade\Filesystem;
class Uploadify extends Base {

    private $image_type = '';
    private $sub_name = '';
    private $fileExt = 'jpg,png,gif,jpeg,bmp,ico';
    private $savePath = 'allimg/';
    private $upload_path = '';

    public function initialize()
    {
        parent::initialize();
        date_default_timezone_set("Asia/Shanghai");
        error_reporting(E_ERROR | E_WARNING);
        header("Content-Type: text/html; charset=utf-8");
        $this->upload_path = 'bbsimg/'.$this->users_id;
    }

    public function imageUp()
    {
        $image_upload_limit_size = intval(tpCache('basic.file_size') * 1024 * 1024);
        // 获取表单上传文件
        $file = request()->file('file');
        if(empty($file)){
            $file = request()->file('upfile');
        }
        $tptype = pathinfo($file->getoriginalName(), PATHINFO_EXTENSION);
        $tptype = strtolower($tptype);
        $newfileExt = explode(",",$this->fileExt); 
        //ico图片文件不进行验证
        if ($tptype != 'ico') {
            if ($image_upload_limit_size <= $file->getSize()) {
                $state = "ERROR：上传文件过大";
                $return_data['state'] = $state;
                return $return_data;
            }
            if (!in_array($tptype, $newfileExt)) {
                $state = "ERROR：上传文件后缀名必须为".$this->fileExt;
                $return_data['state'] = $state;
                return $return_data; 
            }
        }
        //验证图片一句话木马
        $imgstr = @file_get_contents($file->getoriginalName());
        if (false !== $imgstr && preg_match('#<\?php#i', $imgstr)) {
            $state = "ERROR：上传图片不合格";
            $return_data['state'] = $state;
            return $return_data;
        }
        if (!empty($file)) {
            $ossConfig = tpCache('oss');   //还没有完成的功能，后续补上 小潘 by 2020.03.05
            if ($ossConfig['oss_switch']) {
                //这是上传到第三方图片库
            } else {
                $fileName = Filesystem::disk('local')->putFile($this->upload_path, $file);//开始上传操作
                if ($fileName) {
                    $state = "SUCCESS";
                } else {
                    $state = "ERROR" . '上传图片失败！';
                }
                $fileName = str_replace("\/", "/", $fileName);
                $fileName = str_replace("\\", "/", $fileName);   
            }
        }
        $return_data['url'] = '/uploads/'.$fileName; // 支持子目录 
        $return_data['state'] = $state;
        return $return_data;
    }
}